import type { ElMessageBoxOptions, MessageBoxData, messageType } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
import IconSuccess from "virtual:icons/line-md/confirm-circle";
import IconError from "virtual:icons/line-md/close-circle";
import IconInfo from "virtual:icons/line-md/alert-circle";
import IconWarning from "virtual:icons/line-md/alert";

export function useMessage() {
  /**
   * 创建消息
   * @param type 消息类型
   * @param message 消息内容
   */
  function createMessage(type: messageType, message: string, seconds: number = 3) {
    ElMessage({ type, message, grouping: true, showClose: true, duration: seconds * 1000 });
  }

  /**
   * @private
   */
  function _createMessageBox(title: string, message: string, icon: JSX.Element) {
    ElMessageBox({ title, message, icon: icon, showCancelButton: false, confirmButtonText: "确定", draggable: true, closeOnClickModal: true });
  }

  /**
   * 创建成功消息对话框
   * @param message 消息内容
   */
  function createSuccessBox(message: string) {
    _createMessageBox("成功提示", message, <IconSuccess color="#67c23a" />);
  }

  /**
   * 创建提示消息对话框
   * @param message 消息内容
   */
  function createInfoBox(message: string) {
    _createMessageBox("提示", message, <IconInfo color="#909399" />);
  }

  /**
   * 创建警告消息对话框
   * @param message 消息内容
   */
  function createWarningBox(message: string) {
    _createMessageBox("警告提示", message, <IconWarning color="#e6a23c" />);
  }

  /**
   * 创建错误消息对话框
   * @param message 消息内容
   */
  function createErrorBox(message: string) {
    _createMessageBox("错误提示", message, <IconError color="#f56c6c" />);
  }

  /**
   * 创建消息对话框
   * @param type 消息类型
   * @param message 消息
   */
  function createMessageBox(type: messageType, message: string) {
    switch (type) {
      case "error":
        createErrorBox(message);
        break;
      case "success":
        createSuccessBox(message);
        break;
      case "warning":
        createWarningBox(message);
        break;
      case "info":
        createInfoBox(message);
        break;
    }
  }

  function confirmDelete(message: string, ok: (value: MessageBoxData) => void | PromiseLike<void>, options?: ElMessageBoxOptions) {
    options = Object.assign({ confirmButtonText: "删除", confirmButtonClass: "el-button--danger", cancelButtonText: "取消", type: "warning" }, options);
    ElMessageBox.confirm(message, options?.title || "删除确认", options)
      .then(ok)
      .catch((e) => e);
  }

  return {
    createMessage,
    createMessageBox,
    createSuccessBox,
    createInfoBox,
    createWarningBox,
    createErrorBox,
    confirmDelete,
  };
}
